package com.ecreditpal.audio.netty.handler;

import com.google.protobuf.MessageLite;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/24.
 */
@Slf4j
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {
    ScheduledFuture future;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        for (int i = 0; i < 3; i++) {
//            Thread.sleep(5000);
//            ctx.writeAndFlush(new Object());
//        }
       future = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx),0,5000, TimeUnit.MILLISECONDS);

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       if (! (msg instanceof MessageLite)) {
           log.info("heart beat message check");
       }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("error occor while running",cause);
    }

    private class HeartBeatTask implements Runnable{
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {
            this.ctx.writeAndFlush(new Object());
        }
    }
}
